package lime.service;

import java.io.ByteArrayOutputStream;

import lime.common.DQLTemplate;
import lime.common.LimeException;

import org.apache.commons.lang.StringUtils;

import com.documentum.fc.client.IDfSession;
import com.documentum.fc.common.DfException;
import com.documentum.xml.xquery.DfXQuery;
import com.documentum.xml.xquery.IDfXQuery;

public class XQueryService {

	private RepositoryService repositoryService;

	private String storeName;

	public RepositoryService getRepositoryService() {
		return repositoryService;
	}

	public void setRepositoryService(RepositoryService repositoryService) {
		this.repositoryService = repositoryService;
	}

	public String getStoreName() {

		if (StringUtils.isBlank(storeName)) {
			try {
				IDfSession session = repositoryService.getSession();
				DQLTemplate template = new DQLTemplate(session);
				String dql = "select name from dm_extern_free where storage_class = 'xml'";
				storeName = template.queryForString(dql);
			} catch (DfException e) {
				throw new LimeException(e);
			}
		}
		
		return storeName;
	}
	
	public byte[] execute(String queryString) {
		
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		
		try {

			IDfXQuery xquery = new DfXQuery();
			xquery.addStore(getStoreName());
			xquery.setXQueryString(queryString);
			xquery.execute(repositoryService.getSession());
			xquery.getXMLOutputStream(output);
			
		} catch (DfException e) {
			throw new LimeException(e);
		}

		return output.toByteArray();
	}
}